package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SessionThreadLocal;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    private RedisTemplate redisTemplate;

    /**
     * 使用阿里云发送短信接口
     * 此时只是模拟发送
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpServletRequest request){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //SMSUtils.sendMessage("","",user.getPhone(),code.toString());//使用阿里云接口发送短信
        log.info("验证码是：{}",code);

        //将验证码存入域中 方便登录时验证
        //request.getSession().setAttribute(user.getPhone().toString(),code);

        //使用redis缓存存储验证码 并设置有效时间
        redisTemplate.opsForValue().set(user.getPhone().toString(),code,5, TimeUnit.MINUTES);

        return R.success();
    }

    /**
     * 登录验证 并将信息存入session域中
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> user,HttpServletRequest request){

        //使用map接收
        String phone = user.get("phone");
        String code = user.get("code");

        //在域中拿出存入的验证码
        //String codeInSession = (String) request.getSession().getAttribute(phone);
        //在redis中拿到验证码
        Object o = redisTemplate.opsForValue().get(phone);

        //拿域中的验证码与前端携带的验证码进行匹配  匹配上了说明可以存储该信息到数据库
        if (code != null && code.equals(o)){
            //此时查询数据是否存在该手机号
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User u = userService.getOne(userLambdaQueryWrapper);
            //如果不存在就创建对象
            if (u == null){
                u = new User();
                //给对象赋值
                u.setPhone(phone);
                u.setStatus(1);
                userService.save(u);
            }
            //再将该user存入域中，方便到时候能够查看其它页面（过滤器）
            request.getSession().setAttribute("user",u.getId());
            //移除验证码
            request.getSession().removeAttribute(phone);
            //清除redis中验证码
            redisTemplate.delete(phone);

            return R.success(u);
        }

        return R.error("验证码有误");
    }

    /**
     * 退出登录 将session域中的数据删除
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(){
        SessionThreadLocal.removeThreadLocal();
        return R.success();
    }
}
